package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.TaskAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.bean.Scene_Task;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SceneEditActivity extends BaseActivity {
	private LinearLayout mBackL;
	private Button mBackB;
	private Button mNextB;
	private EditText mNameEd;
	private ListView mMessionLv;
	private Button mAddB;
	private TextView tv_statusBar_mian;
	private Scene scene;
	private List<Scene_Task> mScene_Tasks = new ArrayList<Scene_Task>();
	private TaskAdapter mAdapter;
	private SVProgressHUD mSVProgressHUD;
	private int position = -1;
	private String lastName;
	private String newName;
//	private TextView moshi;
      String deviceName="";
	private String sceneId="";
	private String sceneName="";

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.nextstep:
			newName = mNameEd.getText().toString();
			if (newName.length() < 2 || newName.length() > 6) {
				ToastShow.Show(getApplicationContext(), getString(R.string.scene_name_length));
				return;
			}
			boolean e = DeviceManager.getInstance().checkSceneExist(newName);
			if (e) {
				if (position < 0) {
					ToastShow.Show(getApplicationContext(), getString(R.string.scene_name_exists));
					return;
				}
			}
			if (mScene_Tasks.size() == 0) {
				ToastShow.Show(getApplicationContext(), getString(R.string.scene_task_null));
				return;
			}
			// 显示转圈
			mSVProgressHUD = new SVProgressHUD(this);
			mSVProgressHUD.showWithStatus("正在提交");
			// 检查完可以上传 ，先上传场景名称 获取ID
			upLoadScene(newName);
			if (SceneEditActivity.this.position >= 0) {//修改时position不为-1
				if(!newName.equals(sceneName)){//如果输入的名字改了则调用修改接口
					updateSceneName(sceneId,newName);
				}

			}
			break;
		case R.id.add_btn:
			if (DeviceManager.getInstance().getNoLockDevice().size() != 0) {
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(getApplicationContext(), MessionEditActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						startActivityForResult(intent, 1);
					}
				});
			} else {
				ToastShow.Show(getApplicationContext(), "尚未添加设备，无法添加任务");
			}
			break;
		default:
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				int position = msg.arg1;
				mScene_Tasks.remove(position);
				mAdapter.notifyDataSetChanged();
				break;
			case 1:
				// 上传情景成功
				String sceneId = msg.obj.toString();
				Log.i("wmy", "mScene_Tasks.size() = " + mScene_Tasks.size());
				for (int i = 0; i < mScene_Tasks.size(); i++) {
					Log.i("wmy", "" + mScene_Tasks.get(i).getDeviceName() + " " + mScene_Tasks.get(i).getCmdName() + " "
							+ mScene_Tasks.get(i).getDelayed() + " " + mScene_Tasks.get(i).getSceneCmd());
					mScene_Tasks.get(i).setSceneId(sceneId);
					uploadTask(mScene_Tasks.get(i));
				}
				Log.i("wmy", "SceneEditActivity.this.position" + SceneEditActivity.this.position);
				if (SceneEditActivity.this.position >= 0) {//修改时position不为-1
					deleteScene(scene.getSceneId());
				}
				break;
			case 1111:

				break;
			case 2:

				break;
			case 3:
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						getAllScene();
					}
				}, 1000);
				break;
			case 5:
				getAllTasks();
				break;
			case 6:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), getString(R.string.uploadsuccess));
				Intent intent = new Intent();
				intent.putExtra("deviceName", deviceName);
				setResult(0, intent);
				finish();
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_scene_edit;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance().setBackground(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL = $(R.id.back_layout);
		mBackL.setVisibility(View.GONE);
		mBackB = $(R.id.back_btn);
		mBackB.setText("取消");
		mBackB.setVisibility(View.VISIBLE);
		mNextB = $(R.id.nextstep);
		mNextB.setText(getString(R.string.ok));
		mNextB.setVisibility(View.VISIBLE);
		mMessionLv = $(R.id.mession_lv);
		mAddB = $(R.id.add_btn);
		mNameEd = $(R.id.name_ed);
		mBackB.setOnClickListener(this);
		mNextB.setOnClickListener(this);
		mAddB.setOnClickListener(this);
		initData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// initData();
	}

	private void initData() {
		// TODO Auto-generated method stub
		position = getIntent().getIntExtra("position", -1);
		sceneId = getIntent().getStringExtra("sceneId");
		sceneName = getIntent().getStringExtra("sceneName");
		if (position >= 0) {
			scene = DeviceManager.getInstance().getScenes().get(position);
			lastName = scene.getSceneName();
			mNameEd.setText(scene.getSceneName());
			initTestData();
		} else {
			
		}
	}

	private void initTestData() {
		mScene_Tasks = DeviceManager.getInstance().getTasksById(scene.getSceneId());
		if (mAdapter == null) {
			mAdapter = new TaskAdapter(getApplicationContext(), mScene_Tasks,1);//点进去修改时传个0
			mAdapter.setHandler(mHandler);
			mMessionLv.setAdapter(mAdapter);
		} else {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == 0) {
			 deviceName = intent.getStringExtra("device");
			String deviceId = intent.getStringExtra("deviceId");
			String cmd = intent.getStringExtra("cmd");
			String taskName = intent.getStringExtra("mession");
			int hour = Integer.parseInt(intent.getStringExtra("hour"));
			int min = Integer.parseInt(intent.getStringExtra("minute"));
			int sec = Integer.parseInt(intent.getStringExtra("second"));
			int delayTime = sec + min * 60 + hour * 3600;
			for (int i = 0; i < mScene_Tasks.size(); i++) {
				if (mScene_Tasks.get(i).getDeviceId().equals(deviceId)) {
					ToastShow.Show(getApplicationContext(), "设备：" + deviceName + "已设置任务，请先删除原任务再添加");
					return;
				}
			}
			Scene_Task task = new Scene_Task(deviceId, deviceName, taskName, hour, min, sec, delayTime, cmd);
			Log.i("wmy", "添加task前" + mScene_Tasks.size() + task.getSceneCmd());
			mScene_Tasks.add(task);
			Log.i("wmy", "添加一个task" + mScene_Tasks.size() + task.getSceneCmd());
			if (mAdapter == null) {
				mAdapter = new TaskAdapter(getApplicationContext(), mScene_Tasks,0);//初始化时传个0
				mAdapter.setHandler(mHandler);
				mMessionLv.setAdapter(mAdapter);
			} else {
				mAdapter.notifyDataSetChanged();
			}
		}
	}


	private void updateSceneName(String sceneId,String sceneName) {
		RequestParams params = new RequestParams(HttpURL.SCENE_UPDATE_NAME);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("sceneId", sceneId);
			obj.put("sceneName", sceneName);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("Tag", " upLoadScene = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						String sceneId = jo.getString("data");
						Message msg = Message.obtain();
						msg.what = 1111;
						msg.obj = sceneId;
						mHandler.sendMessage(msg);
					} else {
						Message msg = Message.obtain();
						msg.what = 2;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void upLoadScene(String name) {
		RequestParams params = new RequestParams(HttpURL.ADD_SCENE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("sceneName", name);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upLoadScene = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", "上传场景" + result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						String sceneId = jo.getString("data");
						Message msg = Message.obtain();
						msg.what = 1;
						msg.obj = sceneId;
						mHandler.sendMessage(msg);
					} else {
						Message msg = Message.obtain();
						msg.what = 2;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadTask(Scene_Task task) {
		RequestParams params = new RequestParams(HttpURL.HANDLE_SCENE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("cmdName", task.getCmdName()/*+"|"+task.getDeviceName()*/);
			obj.put("delayed", task.getDelayed());
			obj.put("handlType", 1);
			obj.put("sceneId", task.getSceneId());
			obj.put("sceneTaskId", "0");
			obj.put("taksCmd", task.getSceneCmd());
			obj.put("deviceId", task.getDeviceId());
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload task = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", "上传任务" + result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						String sceneId = jo.getString("data");
						Message msg = Message.obtain();
						msg.what = 3;
						msg.obj = sceneId;
						mHandler.sendMessage(msg);
					} else {
						Message msg = Message.obtain();
						msg.what = 4;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void deleteScene(String sceneId) {
		RequestParams params = new RequestParams(HttpURL.DELETE_SCENE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("sceneId", sceneId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("test", " deleteScene obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", "删除场景" + result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地

					} else {

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void getAllScene() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			// if (!Util.isLogin(getApplicationContext())) {
			// return;
			// }
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_LIST);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all scene=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearScene();
							JSONObject data = jsonObject.getJSONObject("data");
							JSONArray ja = data.getJSONArray("lscene");
							if (data.length() != 0) {
								for (int i = 0; i < ja.length(); i++) {
									String sceneId = ja.getJSONObject(i).getString("sceneId");
									String userId = ja.getJSONObject(i).getString("userId");
									String sceneName = ja.getJSONObject(i).getString("sceneName");
									long createTime = ja.getJSONObject(i).getLong("createTime");
									int status = ja.getJSONObject(i).getInt("status");
									String hid = ja.getJSONObject(i).getString("hid");
									Scene scene = new Scene(sceneId, userId, sceneName, status, hid);
									DeviceManager.getInstance().addScene(scene);
								}
							}

							Message msg = Message.obtain();
							msg.what = 5;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							// Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆",
							// Toast.LENGTH_SHORT).show();
							// startActivity(new Intent(getActivity(),
							// LoginActivity.class));
							// finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void getAllTasks() {
		List<Scene> mScenes = DeviceManager.getInstance().getScenes();
		for (int i = 0; i < mScenes.size(); i++) {
			getTaskBySceneId(mScenes.get(i).getSceneId());
		}
	}

	private void getTaskBySceneId(String sceneId) {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			// if (!Util.isLogin(getApplicationContext())) {
			// return;
			// }
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_TASK_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("id", sceneId);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							if (data.length() != 0) {
								// DeviceManager.getInstance().clearTask();
								String sceneId;
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String stId = jo.getString("stId");
									String cmd = jo.getString("cmd");
									String cmdName1 = jo.getString("cmdName");
									String cmdName=cmdName1.split("\\|")[0];
									String deviceName=cmdName1.split("\\|")[1];
									String did = jo.getString("did");
									Device device = DeviceManager.getInstance().getDeviceById(did);
									sceneId = jo.getString("sceneId");
									int delayed = jo.getInt("delayed");
									int hour = delayed / 3600;
									int min = delayed / 60;
									int sec = delayed % 60;
  							     	Scene_Task task = new Scene_Task(stId, delayed, did, cmd, sceneId, cmdName, hour,
											min, sec, device.getMainDeviceId(),deviceName);
									DeviceManager.getInstance().addTask(task);
								}
							}

							Message msg = Message.obtain();
							msg.what = 6;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性

						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}

	}

}
